package com.qianseit.westore.activity.account;

import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

import com.qianseit.westore.AgentApplication;
import com.qianseit.westore.BaseDoFragment;
import com.qianseit.westore.DoActivity;
import com.qianseit.westore.LoginedUser;
import com.qianseit.westore.Run;
import com.qianseit.westore.activity.AgentActivity;
import com.qianseit.westore.http.JsonRequestBean;
import com.qianseit.westore.http.JsonRequestBean.JsonRequestCallback;
import com.qianseit.westore.http.JsonTask;
import com.qianseit.westore.http.JsonTaskHandler;
import com.qianseit.westore.util.ImageLoader;
import com.qianseit.westore.util.loader.VolleyImageLoader;
import com.beautymiracle.androidclient.R;

public class AccountLoginFragment extends BaseDoFragment {
	private static final String PLATFORM_WEIBO = "sina";
	private static final String PLATFORM_WECHAT = "weixin";
	private static final String PLATFORM_QQ = "qzone";

	private EditText mVerifyCodeText;
	private ImageView mVerifyCodeImageView;
	private EditText mUserNameText, mPasswdText;
	private Button mLoginSubmitButton;
	private ImageView mLoginByQQ, mLoginByWechat;
	private ImageView mLoginByAlipay, mLoginByWeibo;

//	private ImageLoader mImageLoader;
	private VolleyImageLoader mVolleyImageLoader;

	public AccountLoginFragment() {
		super();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		mImageLoader = ImageLoader.getInstance(mActivity);
		mVolleyImageLoader = ((AgentApplication)mActivity.getApplication()).getImageLoader();
	}

	@Override
	public void init(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mActionBar.setTitle(R.string.account_login_submit);

		Resources resources = mActivity.getResources();
		rootView = inflater.inflate(R.layout.fragment_account_login, null);
		mUserNameText = (EditText) findViewById(R.id.account_login_username);
		mPasswdText = (EditText) findViewById(R.id.account_login_passwd);
		mVerifyCodeText = (EditText) findViewById(R.id.account_login_vcode_text);
		mVerifyCodeImageView = (ImageView) findViewById(R.id.account_login_vcode_image);
		mLoginSubmitButton = (Button) findViewById(R.id.account_login_submit_button);
		findViewById(R.id.account_login_forget_passwd).setOnClickListener(this);
		findViewById(R.id.account_login_fast_regist).setOnClickListener(this);
		mLoginSubmitButton.setOnClickListener(this);
		mVerifyCodeImageView.setOnClickListener(this);
		autoFillAccountInfo();

		// 第三方登录按钮
		mLoginByQQ = (ImageView) findViewById(R.id.account_login_user_qq);
		mLoginByWechat = (ImageView) findViewById(R.id.account_login_user_wechat);
		mLoginByWeibo = (ImageView) findViewById(R.id.account_login_user_weibo);
		mLoginByAlipay = (ImageView) findViewById(R.id.account_login_user_weibo);
		mLoginByQQ.setOnClickListener(this);
		mLoginByWechat.setOnClickListener(this);
		mLoginByWeibo.setOnClickListener(this);
		mLoginByAlipay.setOnClickListener(this);
		mLoginByQQ.setImageDrawable(Run.getDrawableList(BitmapFactory
				.decodeResource(resources, R.drawable.account_login_use_qq),
				0.5f));
		mLoginByAlipay.setImageDrawable(Run.getDrawableList(
				BitmapFactory.decodeResource(resources,
						R.drawable.account_login_use_alipay), 0.5f));
		mLoginByWechat.setImageDrawable(Run.getDrawableList(
				BitmapFactory.decodeResource(resources,
						R.drawable.account_login_use_wechat), 0.5f));
		mLoginByWeibo.setImageDrawable(Run.getDrawableList(BitmapFactory
				.decodeResource(resources, R.drawable.account_login_use_weibo),
				0.5f));
	}

	@Override
	public void onClick(View v) {
		if (R.id.account_login_fast_regist == v.getId()) {
			startActivityForResult(AgentActivity.intentForFragment(mActivity,
					AgentActivity.FRAGMENT_ACCOUNT_REGIST),
					REQUEST_CODE_USER_REGIST);
		} else if (R.id.account_login_forget_passwd == v.getId()) {
			mActivity.startActivity(AgentActivity.intentForFragment(mActivity,
					AgentActivity.FRAGMENT_FORGET_PASSWORD));
		} else if (mLoginSubmitButton == v) {
			AccountLogin();
		} else if (mLoginByQQ == v) {
			Platform platQQ = ShareSDK.getPlatform(mActivity, QQ.NAME);
			platQQ.setPlatformActionListener(new ThirdLoginListener(PLATFORM_QQ));
			platQQ.SSOSetting(true);
			platQQ.showUser(null);
		} else if (mLoginByWeibo == v) {
			Platform platWB = ShareSDK.getPlatform(mActivity, SinaWeibo.NAME);
			platWB.setPlatformActionListener(new ThirdLoginListener(
					PLATFORM_WEIBO));
			platWB.SSOSetting(true);
			platWB.showUser(null);
		} else if (mVerifyCodeImageView == v) {
			reloadVcodeImage();
		} else if (mLoginByWechat == v) {
			Platform platWX = ShareSDK.getPlatform(mActivity, Wechat.NAME);
			platWX.setPlatformActionListener(new ThirdLoginListener(
					PLATFORM_WECHAT));
			platWX.showUser(null);
		} else {
			super.onClick(v);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_USER_REGIST
				&& resultCode == Activity.RESULT_OK) {
			autoFillAccountInfo();
			onClick(mLoginSubmitButton);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	// 恢复登录用户名和密码
	private void autoFillAccountInfo() {
		if (!TextUtils.isEmpty(Run.loadOptionString(mActivity,
				Run.pk_logined_username, Run.EMPTY_STR)))
			mUserNameText.setText(Run.loadOptionString(mActivity,
					Run.pk_logined_username, Run.EMPTY_STR));
		if (!TextUtils.isEmpty(Run.loadOptionString(mActivity,
				Run.pk_logined_user_password, Run.EMPTY_STR)))
			mPasswdText.setText(Run.loadOptionString(mActivity,
					Run.pk_logined_user_password, Run.EMPTY_STR));
	}

	// 注册用户
	private void AccountLogin() {
		if (TextUtils.isEmpty(mUserNameText.getText().toString())) {
			mUserNameText.requestFocus();
		} else if (TextUtils.isEmpty(mPasswdText.getText().toString())) {
			mPasswdText.requestFocus();
		} else if (mVerifyCodeText.isShown()
				&& TextUtils.isEmpty(mVerifyCodeText.getText().toString())) {
			mVerifyCodeText.requestFocus();
		} else {
			Run.hideSoftInputMethod(mActivity, mUserNameText);
			Run.hideSoftInputMethod(mActivity, mPasswdText);
			Run.hideSoftInputMethod(mActivity, mVerifyCodeText);
			Run.excuteJsonTask(new JsonTask(), new UserLoginTask(
					(DoActivity) mActivity, mUserNameText.getText().toString(),
					mPasswdText.getText().toString(), mVerifyCodeText.getText()
							.toString(), new JsonRequestCallback() {
						@Override
						public void task_response(String jsonStr) {
							userLoginCallback(jsonStr);
						}
					}));
		}
	}

	/**
	 * 用户登录
	 * 
	 * @param json_str
	 */
	private void userLoginCallback(String json_str) {
		((DoActivity) mActivity).hideLoadingDialog_mt();
		try {
			JSONObject all = new JSONObject(json_str);
			if (Run.checkRequestJson(mActivity, all)) {
				userLoginSuccess(all);
			} else {
				JSONObject data = all.optJSONObject("data");
				if (data.optInt("needVcode") == 1) {
					// ((View) mPasswdText.getParent())
					// .setBackgroundResource(R.drawable.account_login_list_middlebg);
					findViewById(R.id.account_login_vcode).setVisibility(
							View.VISIBLE);
					reloadVcodeImage();
				}
			}
		} catch (Exception e) {
		}
	}

	/**
	 * 用户登录成功
	 * 
	 * @param all
	 */
	private void userLoginSuccess(JSONObject all) throws Exception {
		LoginedUser user = AgentApplication.getLoginedUser(mActivity);
		user.setIsLogined(true);
		user.setUserInfo(all.getJSONObject("data"));
		// 保存用户名，密码
		Run.savePrefs(mActivity, Run.pk_logined_username, mUserNameText
				.getText().toString());
		Run.savePrefs(mActivity, Run.pk_logined_user_password, mPasswdText
				.getText().toString());

		// 登录成功
		mActivity.setResult(Activity.RESULT_OK);
		mActivity.finish();
	}

	private void reloadVcodeImage() {
		String vcodeUrl = Run.buildString(Run.VCODE_URL,
				System.currentTimeMillis());
//		Uri uri = Uri.parse(vcodeUrl);
//		mVerifyCodeImageView.setTag(uri);
//		mImageLoader.showImage(mVerifyCodeImageView, uri);
		mVolleyImageLoader.showImage(mVerifyCodeImageView, vcodeUrl);
	}

	public static class UserLoginTask implements JsonTaskHandler {
		private String username, passwd, vcode;
		private DoActivity activity;
		private JsonRequestCallback callback;

		public UserLoginTask(DoActivity activity, String username,
				String passwd, String vCode, JsonRequestCallback callback) {
			this.activity = activity;
			this.username = username;
			this.passwd = passwd;
			this.vcode = vCode;
			this.callback = callback;
		}

		@Override
		public JsonRequestBean task_request() {
			if (activity != null)
				activity.showCancelableLoadingDialog();
			JsonRequestBean rb = new JsonRequestBean(Run.API_URL,
					"mobileapi.passport.post_login").addParams("uname",
					username).addParams("password", passwd);
			if (!TextUtils.isEmpty(vcode))
				rb.addParams("verifycode", vcode);
			return rb;
		}

		@Override
		public void task_response(String json_str) {
			if (callback != null)
				callback.task_response(json_str);
		}
	}

	private class ThirdUserLoginTask implements JsonTaskHandler {
		private String platformName, openid, realname, nickname;;

		public ThirdUserLoginTask(String platName, String openid,
				String realname, String nickname) {
			this.platformName = platName;
			this.openid = openid;
			this.realname = realname;
			this.nickname = nickname;
		}

		@Override
		public JsonRequestBean task_request() {
			showCancelableLoadingDialog();
			JsonRequestBean bean = new JsonRequestBean(Run.API_URL,
					"mobileapi.passport.trust_login").addParams(
					"provider_code", platformName).addParams("openid", openid);
			if (!TextUtils.isEmpty(nickname))
				bean.addParams("nickname", nickname);
			if (!TextUtils.isEmpty(realname))
				bean.addParams("realname", realname);
			return bean;
		}

		@Override
		public void task_response(String json_str) {
			hideLoadingDialog_mt();
			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					userLoginSuccess(all);
				}
			} catch (Exception e) {
			}
		}
	}

	private class ThirdLoginListener implements PlatformActionListener {
		private String platformName;

		public ThirdLoginListener(String platName) {
			this.platformName = platName;
		}

		@Override
		public void onError(Platform arg0, int arg1, Throwable arg2) {
			arg2.printStackTrace();
		}

		@Override
		public void onComplete(Platform arg0, int arg1,
				HashMap<String, Object> arg2) {
			if (PLATFORM_WEIBO.equals(platformName)) {
				String openid = arg2.get("idstr").toString();
				String realname = arg2.get("screen_name").toString();
				String nickname = arg2.get("name").toString();
				Run.excuteJsonTask(new JsonTask(), new ThirdUserLoginTask(
						platformName, openid, realname, nickname));
			}
		}

		@Override
		public void onCancel(Platform arg0, int arg1) {
			Run.log("onCancel:", arg1);
		}

	}
}
